<template>
  <div class="character-list-page">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="flex items-center justify-between">
        <div>
          <h1 class="text-2xl font-bold text-gray-900">AI角色扮演</h1>
          <p class="text-gray-600 mt-1">选择一个角色开始对话，或创建新的角色</p>
        </div>
        <div class="flex gap-3">
          <n-button
            type="primary"
            :loading="loading"
            @click="$router.push({ name: 'CharacterCreate' })"
          >
            <template #icon>
              <svg
                class="w-4 h-4"
                fill="none"
                stroke="currentColor"
                viewBox="0 0 24 24"
              >
                <path
                  stroke-linecap="round"
                  stroke-linejoin="round"
                  stroke-width="2"
                  d="M12 4v16m8-8H4"
                ></path>
              </svg>
            </template>
            创建角色
          </n-button>
          <n-button @click="$router.push({ name: 'CharacterManage' })">
            管理角色
          </n-button>
        </div>
      </div>
    </div>

    <!-- 错误提示 -->
    <n-alert
      v-if="error"
      type="error"
      :title="error"
      closable
      class="mb-6"
      @close="clearError"
    />

    <!-- 角色列表 -->
    <div v-if="loading && characters.length === 0" class="text-center py-12">
      <n-spin size="large" />
      <p class="text-gray-500 mt-4">加载中...</p>
    </div>

    <div v-else-if="activeCharacters.length === 0" class="empty-state">
      <div class="text-center py-12">
        <svg
          class="w-16 h-16 text-gray-400 mx-auto mb-4"
          fill="none"
          stroke="currentColor"
          viewBox="0 0 24 24"
        >
          <path
            stroke-linecap="round"
            stroke-linejoin="round"
            stroke-width="2"
            d="M17 20h5v-2a3 3 0 00-5.356-1.857M17 20H7m10 0v-2c0-.656-.126-1.283-.356-1.857M7 20H2v-2a3 3 0 015.356-1.857M7 20v-2c0-.656.126-1.283.356-1.857m0 0a5.002 5.002 0 019.288 0M15 7a3 3 0 11-6 0 3 3 0 016 0zm6 3a2 2 0 11-4 0 2 2 0 014 0zM7 10a2 2 0 11-4 0 2 2 0 014 0z"
          ></path>
        </svg>
        <h3 class="text-lg font-medium text-gray-900 mb-2">还没有角色</h3>
        <p class="text-gray-500 mb-6">
          创建您的第一个AI角色，开始精彩的对话吧！
        </p>
        <n-button
          type="primary"
          size="large"
          @click="$router.push({ name: 'CharacterCreate' })"
        >
          创建第一个角色
        </n-button>
      </div>
    </div>

    <div v-else class="character-grid">
      <div
        v-for="character in activeCharacters"
        :key="character.id"
        class="character-card"
        @click="selectCharacter(character)"
      >
        <div class="character-avatar">
          <img
            v-if="character.avatar"
            :src="character.avatar"
            :alt="character.name"
            class="w-full h-full object-cover"
          />
          <div v-else class="avatar-placeholder">
            {{ character.name.charAt(0) }}
          </div>
        </div>

        <div class="character-info">
          <h3 class="character-name">{{ character.name }}</h3>
          <div class="character-personality">
            <n-tag
              v-for="trait in character.personality.slice(0, 3)"
              :key="trait"
              size="small"
              type="info"
              class="mr-1 mb-1"
            >
              {{ trait }}
            </n-tag>
          </div>
          <p class="character-description">{{ character.speakingStyle }}</p>
        </div>

        <div class="character-actions">
          <n-button
            type="primary"
            size="small"
            @click.stop="startChat(character)"
          >
            开始对话
          </n-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { storeToRefs } from 'pinia';
import { NButton, NAlert, NSpin, NTag } from 'naive-ui';
import { useRoleplayStore } from '@/stores/roleplay';
import type { Character } from '@/types/roleplay';

const router = useRouter();
const store = useRoleplayStore();

// 从store中获取状态 - 使用storeToRefs保持响应性

const { characters, activeCharacters, loading, error } = storeToRefs(store);

const {
  loadCharacters,
  selectCharacter: storeSelectCharacter,
  createConversation,
  clearError,
} = store;

// 选择角色
const selectCharacter = async (character: Character) => {
  await storeSelectCharacter(character);
  router.push({
    name: 'CharacterManage',
  });
};

// 开始对话
const startChat = async (character: Character) => {
  try {
    await storeSelectCharacter(character);

    // 创建新对话
    const conversation = await createConversation(character.id);

    // 跳转到对话页面
    router.push({
      name: 'Chat',
      params: {
        characterId: character.id,
        conversationId: conversation.id,
      },
    });
  } catch (error) {
    console.error('开始对话失败:', error);
  }
};

// 页面加载时获取角色列表
onMounted(async () => {
  console.log('开始加载角色列表...');
  await loadCharacters();
  console.log('角色列表加载完成:', characters.value);
  console.log('活跃角色列表:', activeCharacters.value);
});
</script>

<style scoped>
@reference "@/styles/app.css";

.character-list-page {
  @apply max-w-7xl mx-auto px-4 py-6;
}

.page-header {
  @apply mb-8;
}

.character-grid {
  @apply grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 xl:grid-cols-4 gap-6;
}

.character-card {
  @apply bg-white rounded-lg shadow-md hover:shadow-lg transition-shadow duration-200 cursor-pointer border border-gray-200 overflow-hidden;
}

.character-card:hover {
  @apply transform -translate-y-1;
}

.character-avatar {
  @apply w-full h-48 bg-gray-100 flex items-center justify-center;
}

.avatar-placeholder {
  @apply w-20 h-20 bg-blue-500 text-white rounded-full flex items-center justify-center text-2xl font-bold;
}

.character-info {
  @apply p-4;
}

.character-name {
  @apply text-lg font-semibold text-gray-900 mb-2;
}

.character-personality {
  @apply mb-3;
}

.character-description {
  @apply text-sm text-gray-600 line-clamp-2;
}

.character-actions {
  @apply p-4 pt-0;
}

.empty-state {
  @apply bg-white rounded-lg shadow-sm border border-gray-200;
}
</style>
